package day01;

import java.util.Arrays;

public class MyArrayList<E> {
    private Object[] elementData = {};
    private int size = 0;

    /**
     * 将元素追加到数组中
     * @param e 被添加的元素
     * @return true 表示元素被追加了
     */
    // add("Tom") add("Jerry") add("Jerry")
    public boolean add(E e){
        //Capacity: 容量
        // ensure: 确认
        //数组满了再扩容
        ensureCapacity();
        elementData[size++] = e;
        return true;
    }

    private void ensureCapacity(){
        if (size == 0){
            elementData = new Object[10];
        }else if (size == elementData.length) {
            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1); //扩容1.5倍
            elementData = Arrays.copyOf(elementData, newCapacity);
        }
    }

    public boolean add(int index, E e){
        if (index<0 || index > size){
            throw new IndexOutOfBoundsException("越界:"+index);
        }
        if (index == size){
            return add(e);
        }
        //确认容量， 以后再移动添加
        ensureCapacity();
        for(int i=size-1; i>=index; i--){
            elementData[i+1]=elementData[i];
        }
        elementData[index] = e;
        size++;
        return true;
    }

    public E get(int index){
        return (E)elementData[index];
    }

    public int size(){
        return size;
    }

    public E delete(int index){
        if (index<0 || index >= size){
            throw new IndexOutOfBoundsException("越界");
        }
        E e = (E)elementData[index];
        for(int i=index; i<size-1;i++){
            elementData[i]=elementData[i+1];
        }
        size--;
        return e;
    }

    /**
     * [Tom, Jerry, Andy, Mac]
     * @return
     */
    public String toString(){
        if (size == 0){
            return "[]";
        }
        StringBuilder buf = new StringBuilder("[");
        buf.append(elementData[0]);
        for(int i=1; i<size; i++){
            buf.append(", ").append(elementData[i]);
        }
        return buf.append("]") .toString();
    }
}
